#include <fstream>
#include <vector>
#include <string>
#include <iostream>

void writeToCsv(const std::string& filename, const std::vector<std::vector<std::string>>& data) {
    std::ofstream file(filename,std::ios::app);
    if (!file.is_open()) {
        throw std::runtime_error("无法打开文件: " + filename);
    }

    for (const auto& row : data) {
        for (size_t i = 0; i < row.size(); ++i) {
            // 处理包含逗号或引号的值
            std::string value = row[i];
            bool needsQuotes = (value.find(',') != std::string::npos || 
                               value.find('"') != std::string::npos || 
                               value.find('\n') != std::string::npos);
            
            if (needsQuotes) {
                file << '"';
                // 转义引号
                for (char c : value) {
                    if (c == '"') file << '"';
                    file << c;
                }
                file << '"';
            } else {
                file << value;
            }
            
            if (i != row.size() - 1) {
                file << ','; // 分隔符
            }
        }
        file << '\n'; // 换行符
    }

    file.close();
}

// 使用示例
int main() {
    std::vector<std::vector<std::string>> headerdata = {
        {"姓名", "年龄", "职业"},
    };

    try {
        writeToCsv("output.csv", headerdata);
        std::cout << "CSV文件写入成功!" << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "错误: " << e.what() << std::endl;
    }
        std::vector<std::vector<std::string>> data = {
        {"张三", "25", "工程师"},
        {"李四", "30", "医生"},
        {"王五", "22", "学生"}
    };
     try {
        writeToCsv("output.csv", data);
        std::cout << "CSV文件写入成功!" << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "错误: " << e.what() << std::endl;
    }

    return 0;
}